package com.commerce.user.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.commerce.common.utils.Result;
import com.commerce.user.config.AliOSSConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
@CrossOrigin(originPatterns = "*", allowCredentials = "true")
public class FileUploadController {
    
    private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);
    
    @Autowired
    private OSS ossClient;
    
    @Autowired
    private AliOSSConfig aliOSSConfig;
    
    /**
     * 通用文件上传接口
     */
    @PostMapping
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            logger.warn("上传文件为空");
            return Result.error(400, "请选择要上传的文件");
        }

        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            logger.warn("上传的文件类型不是图片: {}", contentType);
            return Result.error(400, "只能上传图片文件");
        }

        // 生成唯一的文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";
        String filename = "products/" + UUID.randomUUID().toString() + extension;

        try {
            // 上传文件到OSS
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                aliOSSConfig.getBucketName(),
                filename,
                file.getInputStream()
            );
            ossClient.putObject(putObjectRequest);

            // 生成文件访问URL
            String fileUrl = "https://" + aliOSSConfig.getBucketName() + "." + aliOSSConfig.getEndpoint() + "/" + filename;
            logger.info("文件上传成功：{}", fileUrl);

            return Result.success(fileUrl);
        } catch (Exception e) {
            logger.error("文件上传到OSS失败", e);
            return Result.error(500, "文件上传失败：" + e.getMessage());
        }
    }

    @PostMapping("/avatar")
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file,
                                     HttpServletRequest request,
                                     @RequestHeader(value = "Authorization", required = false) String authHeader) {
        logger.info("开始处理头像上传请求，文件大小: {}", file.getSize());

        // 验证用户登录状态 - 支持Token和Session两种方式
        boolean isAuthenticated = false;

        // 首先尝试Token认证
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            logger.info("使用Token认证: {}", token.substring(0, Math.min(token.length(), 10)) + "...");
            // 这里简单验证token不为空，实际项目中应该验证token有效性
            isAuthenticated = !token.isEmpty();
        } else {
            // 回退到Session认证
            HttpSession session = request.getSession(false);
            if (session != null && session.getAttribute("userId") != null) {
                isAuthenticated = true;
                logger.info("使用Session认证");
            }
        }

        if (!isAuthenticated) {
            logger.warn("未登录用户尝试上传头像");
            return Result.error(403, "请先登录后再上传头像");
        }
        
        // 检查文件是否为空
        if (file.isEmpty()) {
            logger.warn("上传文件为空");
            return Result.error(400, "请选择要上传的文件");
        }

        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            logger.warn("上传的文件类型不是图片: {}", contentType);
            return Result.error(400, "只能上传图片文件");
        }

        // 生成唯一的文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";
        String filename = "avatars/" + UUID.randomUUID().toString() + extension;

        try {
            // 上传文件到OSS
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                aliOSSConfig.getBucketName(),
                filename,
                file.getInputStream()
            );
            ossClient.putObject(putObjectRequest);

            // 生成文件访问URL
            String fileUrl = "https://" + aliOSSConfig.getBucketName() + "." + aliOSSConfig.getEndpoint() + "/" + filename;
            logger.info("文件上传成功：{}", fileUrl);

            return Result.success(fileUrl);
        } catch (Exception e) {
            logger.error("文件上传到OSS失败", e);
            return Result.error(500, "文件上传失败：" + e.getMessage());
        }
    }
} 